package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.CHScrollCalculateView;
import com.lzx.iteam.widget.CHScrollFieldView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;

import static com.lzx.iteam.DialerApp.mContext;
import static com.lzx.iteam.DialerApp.map;
import static com.lzx.iteam.util.StringUtil.floatFormat;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2017年 01月 14日
 * Time: 下午2:26
 *
 * @QQ : 1234567890
 * **********************************
 *
 * 考勤表、工资合计、工资单生成页面
 */
public class SalaryCalculateActivity extends MyBaseActivity {

    @FindViewById(id = R.id.ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.tv_title_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.tv_title_right2)
    private TextView mTvEdit;
    @FindViewById(id = R.id.tv_title_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.ch_scroll_excle_item)
    private CHScrollCalculateView mScrollViewCalculate;
    @FindViewById(id = R.id.ll_excle_item)
    private LinearLayout mLayoutTitle;
    @FindViewById(id = R.id.lv_salary_excle)
    private ListView mListView;

    //方便测试，直接写的public
    public HorizontalScrollView mTouchView;
    // 所有的 scrollview
    private List<CHScrollCalculateView> mHScrollViews = new ArrayList<>();
    // 考勤表数据
    private ArrayList<SalaryAttendanceBean> mAttendanceData = new ArrayList<>();

    // 成员基本工资数据
    private ArrayList<SalaryMemberSalaryBean> mMemberSalary = new ArrayList<>();
    private LinkedHashMap<String,SalaryMemberSalaryBean> mMemberSalaryMap = new LinkedHashMap<>();
    // 基本工资 和 自定义字段 标题
    private ArrayList<SalaryFieldBean> mMemberField = new ArrayList<>();

    // 列表显示数据
    private ArrayList<Object> mDatas = new ArrayList<>();
    // 备份考勤表数据
    private ArrayList<Object> mDataAttendance = new ArrayList<>();
    // 备份核对考勤表后的数据
    private ArrayList<Object> mDataSalary = new ArrayList<>();
    // 第一行标题栏数据（日薪 出勤工资 饭补 出差。。。。。。）
    private ArrayList<String> mTitleData = new ArrayList<>();
    // 工资合计数据
    private SalaryAllBean mSumBean;
    // 考勤规则
    private SalaryRuleBean mRuleData;
    // 选择的日期
    private DateData mSelectDate;
    private MyAdapter mAdapter;

    /**
     * 0：默认
     * 1：工资单列表进入
     */
    private int mFlag;
    /**
     * 生成步骤
     * 2：核对考勤表
     * 3：核对工资单
     * 4：生成工资表
     * 5：查看工资表
     */
    private String mGroupId;
    private String mSalaryId;
    private int mStep = 2;
    private int mPositionX = -1;
    private int mPositionY = -1;

    private final int GET_ATTENDANCE_LIST = 30001;
    private final int SAVE_MEMBER_SALARY = 30002;
    private final int GET_MEMBER_SALARY = 30003;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            waitDlgDismiss();
            if (msg.arg1 == 0){
                switch (msg.what){
                    case GET_ATTENDANCE_LIST:
                        mAttendanceData = (ArrayList<SalaryAttendanceBean>) msg.obj;
                        for (int i = 0; i < mAttendanceData.size(); i++) {
                            mDatas.add(mAttendanceData.get(i));
                        }
                        setAttendanceTitle();
                        break;
                    case SAVE_MEMBER_SALARY:
                        showShortToast("保存成功");
                        Intent intent = new Intent(mActivity,SalaryMainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                        break;
                    case GET_MEMBER_SALARY:
                        // 列表数据
                        ArrayList<SalaryAllBean> mSalaryAllData = (ArrayList<SalaryAllBean>) msg.obj;// 列表数据
                        if (mSalaryAllData != null && mSalaryAllData.size() > 0) {
                            // 工资和自定义字段
                            mMemberField.clear();
                            mMemberField.add(new SalaryFieldBean("基本工资"));
                            SalaryFieldBean[] fieldTitles = mSalaryAllData.get(0).getSalary_fields();
                            for (int i = 0; i < fieldTitles.length; i++) {
                                mMemberField.add(fieldTitles[i]);
                            }
                            float sum_sum_salary = 0;
                            float sum_actual_salary = 0;
                            mSumBean = new SalaryAllBean();
                            for (int i = 0; i < mSalaryAllData.size(); i++) {
                                //
                                SalaryAllBean bean = mSalaryAllData.get(i);
                                LinkedHashMap<String,SalaryFieldBean> memberFields = new LinkedHashMap<>();
                                memberFields.put("基本工资",new SalaryFieldBean("基本工资",bean.getBase_salary() + ""));
                                SalaryFieldBean[] fields = bean.getSalary_fields();
                                for (int j = 0; j < fields.length; j++) {
                                    memberFields.put(fields[j].getName(),fields[j]);
                                }
                                bean.setFileds(memberFields);

                                mSumBean.setFileds(memberFields);
                                sum_sum_salary += bean.getSum_salary();
                                sum_actual_salary += bean.getActual_salary();

                                mDatas.add(bean);
                            }

                            // 计算合计数据
                            if (mSalaryAllData.size() > 0){
                                mSumBean.setUser_name("合计");
                                mSumBean.set_id("0");
                                mSumBean.setSum_salary(sum_sum_salary);
                                mSumBean.setActual_salary(sum_actual_salary);
                                mDatas.add(mSumBean);
                            }
                            setSalaryFormTitle();
                        }else{
                            showShortToast("暂无数据");
                        }
                        break;

                }
            }else{
                Toast.makeText(mActivity, (String) msg.obj,
                      Toast.LENGTH_LONG).show();
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState,R.layout.salary_calculate_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
        mTvEdit.setOnClickListener(this);
    }

    @Override
    public void initData() {

        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mRuleData = (SalaryRuleBean) intent.getSerializableExtra("salary_rule");
        mSelectDate = (DateData) intent.getSerializableExtra("month");
        mFlag = intent.getIntExtra("action_type",0);
        if (mFlag == 1){
            mStep = 5;
            mSalaryId = intent.getStringExtra("salary_id");
            getMemberSalary();
        } else{
            mMemberSalary = (ArrayList<SalaryMemberSalaryBean>) intent.getSerializableExtra("member_salary");
            mMemberField = (ArrayList<SalaryFieldBean>) intent.getSerializableExtra("member_salary_fileds");
            mMemberSalaryMap.clear();
            for (int i = 0; i < mMemberSalary.size(); i++) {
                SalaryMemberSalaryBean bean = mMemberSalary.get(i);
                mMemberSalaryMap.put(bean.get_id(),bean);
            }
            getAttendanceList();
        }
        setStepData();


    }

    /**
     * 设置考勤标题
     */
    private void setAttendanceTitle(){

        mHScrollViews.add(mScrollViewCalculate);

        mTitleData.clear();
        mTitleData.add("工作日");
        mTitleData.add("在岗");
        mTitleData.add("出差");
        mTitleData.add("带薪假期");
        mTitleData.add("请假");
        mTitleData.add("外出");
        mTitleData.add("迟到");
        mTitleData.add("早退");
        mTitleData.add("旷工");
        mTitleData.add("加班");

        setListData();
    }

    /**
     * 设置核对考勤标题
     */
    private void setCheckTitle(){

        mHScrollViews.add(mScrollViewCalculate);

        mTitleData.clear();
        mTitleData.add("日薪");
        mTitleData.add("出勤工资");
        mTitleData.add("饭补");
        mTitleData.add("出差补贴");
        mTitleData.add("加班补贴");
        mTitleData.add("迟到扣款");
        mTitleData.add("早退扣款");
        mTitleData.add("旷工扣款");
        mTitleData.add("工资增减项");

        setListData();
    }


    /**
     * 设置核对考勤标题
     */
    private void setSalaryFormTitle(){

        mHScrollViews.add(mScrollViewCalculate);

        mTitleData.clear();
        for (int i = 0; i < mMemberField.size(); i++) {
            mTitleData.add(mMemberField.get(i).getName());
        }
        mTitleData.add("出勤工资");
        mTitleData.add("饭补");
        mTitleData.add("出差补贴");
        mTitleData.add("加班补贴");
        mTitleData.add("迟到扣款");
        mTitleData.add("早退扣款");
        mTitleData.add("旷工扣款");
        mTitleData.add("工资增减项");

        mTitleData.add("工资合计");

        mTitleData.add("个人养老");
        mTitleData.add("个人医疗");
        mTitleData.add("个人失业");
        mTitleData.add("公积金");
        mTitleData.add("扣税");
        mTitleData.add("实发工资");

        setListData();
    }


    /**
     * 设置列表信息
     */
    private void setListData(){

        mLayoutTitle.removeAllViews();
        for (int i = 0; i < mTitleData.size(); i++) {
            TextView tv = new TextView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(this, 79.4f), ViewGroup.LayoutParams.MATCH_PARENT);
            tv.setGravity(Gravity.CENTER);
            tv.setLayoutParams(params);
            tv.setText(mTitleData.get(i));
            tv.setTextColor(getResources().getColor(R.color.black));
            mLayoutTitle.addView(tv);
            View line = new View(mActivity);
            LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), ViewGroup.LayoutParams.MATCH_PARENT);
            line.setLayoutParams(lineParams);
            line.setBackgroundResource(R.color.excle_line);
            mLayoutTitle.addView(line);
        }

        mAdapter = new MyAdapter();
        mListView.setAdapter(mAdapter);

    }

    /**
     * 核对考勤表
     */
    private void checkAttendanceForm(){

        if (mMemberSalaryMap == null) {
            showShortToast("基本工资数据出错");
            return;
        }

        mDataAttendance.clear();
        mDataAttendance.addAll(mDatas);
        mDatas.clear();

        for (int i = 0; i < mDataAttendance.size(); i++) {
            // 考勤表
            SalaryAttendanceBean attendance = (SalaryAttendanceBean) mDataAttendance.get(i);
            String attendance_id = attendance.get_id();
            // 所有的数据bean
            SalaryAllBean allData = new SalaryAllBean();
            allData.set_id(attendance_id);
            allData.setUser_name(attendance.getUser_name());
            // 基本工资 自定义字段 和 养老基数、医疗基数、公积金基数
            SalaryMemberSalaryBean salaryBean = mMemberSalaryMap.get(attendance_id);
            // 基本工资 自定义字段内容
            LinkedHashMap<String,SalaryFieldBean> fileds = salaryBean.getFieldList();

            // 基本工资总额
            float baseAllSalary = 0;
            Iterator iterator = fileds.keySet().iterator();
            while (iterator.hasNext()){
                Object object = iterator.next();
                SalaryFieldBean filed = fileds.get(object);
                String money = filed.getMoney();
                if (StringUtil.isEmpty(money)){
                    baseAllSalary += 0;
                }else{
                    baseAllSalary += Float.parseFloat(money);
                }
            }
            // 基本工资 自定义字段内容
            allData.setFileds(fileds);

            /*// 基本工资
            if (fileds.get("基本工资") != null) {
                String base = fileds.get("基本工资").getMoney();
                if (StringUtil.isEmpty(base)){
                    allData.setBase_salary(Float.parseFloat(base));
                }
            }*/

            // 日薪
            float day_salary = 0;
            float total = attendance.getTotal();
            if (total != 0){
                day_salary = baseAllSalary/total;
            }
            allData.setDay_salary(day_salary);

            // 出勤工资
            float work_salary = 0;
            work_salary = day_salary*(attendance.getWork_day() + attendance.getPaid_holidays() + attendance.getApproval_business() + attendance.getApproval_out());
            allData.setWork_salary(work_salary);

            // 饭补
            float meal_allowance = 0;
            meal_allowance = (attendance.getWork_day() + attendance.getApproval_out() ) * mRuleData.getMeal_allowance();
            allData.setMeal_allowance(meal_allowance);

            // 出差补贴
            float business_allowance = 0;
            business_allowance = attendance.getApproval_business() * mRuleData.getBusiness_allowance();
            allData.setBusiness_allowance(business_allowance);

            // 加班补贴
            float overtime_allowance = 0;
            overtime_allowance = day_salary * attendance.getOver_time() * mRuleData.getOvertime_allowance();
            allData.setOvertime_allowance(overtime_allowance);

            // 迟到扣款
            float late_fine = 0;
            late_fine = attendance.getWork_be_late_count() * mRuleData.getLate_fine();
            allData.setLate_fine(late_fine);

            // 早退扣款
            float leave_fine = 0;
            leave_fine = attendance.getWork_leave_early_count() * mRuleData.getLeave_fine();
            allData.setLeave_fine(leave_fine);

            // 旷工扣款
            float absent_fine = 0;
            absent_fine = day_salary * attendance.getUn_work() * mRuleData.getAbsent_fine();
            allData.setAbsent_fine(absent_fine);

            /*// 工资合计
            float sum_salary = 0;
            sum_salary = work_salary + meal_allowance + overtime_allowance + business_allowance + allData.getPlus_or_minus()
                  - late_fine - leave_fine - absent_fine;
            allData.setSum_salary(sum_salary);*/

            // 个人养老
            float pension = 0;
            pension = salaryBean.getPension_base() * mRuleData.getP_pension_pc();
            allData.setPension(pension);
            // 个人医疗
            float medical = 0;
            if (salaryBean.getMedical_base() != 0){
                medical = salaryBean.getMedical_base() * mRuleData.getP_medical_pc() + mRuleData.getP_medical_count();
            }
            allData.setMedical(medical);

            // 个人失业
            float unemployment = 0;
            unemployment = salaryBean.getPension_base() * mRuleData.getP_unemployment_pc();
            allData.setUnemployment(unemployment);

            // 公积金
            float provident_fund = 0;
            provident_fund = salaryBean.getProvident_fund_base() * mRuleData.getP_provident_fund_pc();
            allData.setProvident_fund(StringUtil.floatFormatToInt(provident_fund));

            mDatas.add(allData);
        }

    }

    /**
     * 生成工资单
     */
    private void createSalaryForm(){

        mDataSalary.clear();
        mDataSalary.addAll(mDatas);

        // 合计工资数据
        float sum_sum_salary = 0;
        float sum_actual_salary = 0;
        mSumBean = new SalaryAllBean();

        for (int i = 0; i < mDatas.size(); i++) {
            SalaryAllBean allData = (SalaryAllBean) mDatas.get(i);

            if (i == 0){
                mSumBean.setFileds(allData.getFileds());
            }

            // 工资合计
            float sum_salary = allData.getWork_salary() + allData.getMeal_allowance() + allData.getOvertime_allowance() + allData.getBusiness_allowance()
                  - allData.getLate_fine() - allData.getLeave_fine() - allData.getAbsent_fine();
            if (allData.getPlus_or_minus() != 0){
                sum_salary += allData.getPlus_or_minus();
            }
            ((SalaryAllBean) mDatas.get(i)).setSum_salary(sum_salary);
            sum_sum_salary += sum_salary;
            // 扣税
            float salary_tax = 0;
            int tax = mRuleData.getSalary_tax();
            float actualSalaryBeforeTax = sum_salary - allData.getPension() - allData.getMedical() - allData.getUnemployment() - allData.getProvident_fund();
            if (tax == 1){
                float  salaryBeforeTax = actualSalaryBeforeTax - 3500;
                if (salaryBeforeTax >= 80000){
                    salary_tax = salaryBeforeTax * 0.45f - 13505;
                }else if (salaryBeforeTax >= 55000){
                    salary_tax = salaryBeforeTax * 0.35f - 5505;
                }else if (salaryBeforeTax >= 35000){
                    salary_tax = salaryBeforeTax * 0.3f - 2755;
                }else if (salaryBeforeTax >= 9000){
                    salary_tax = salaryBeforeTax * 0.25f - 1005;
                }else if (salaryBeforeTax >= 4500){
                    salary_tax = salaryBeforeTax * 0.2f - 555;
                }else if (salaryBeforeTax >= 1500){
                    salary_tax = salaryBeforeTax * 0.1f - 105;
                }else if (salaryBeforeTax >= 0){
                    salary_tax = salaryBeforeTax * 0.03f;
                }else {
                    salary_tax = 0;
                }
            }
            ((SalaryAllBean) mDatas.get(i)).setSalary_tax(salary_tax);

            // 实发工资
            float actual_salary = 0;
            actual_salary = actualSalaryBeforeTax - salary_tax;
            ((SalaryAllBean) mDatas.get(i)).setActual_salary(actual_salary);
            sum_actual_salary += actual_salary;

        }
        // 计算合计数据
        if (mDatas.size() > 0){
            mSumBean.setUser_name("合计");
            mSumBean.set_id("0");
            mSumBean.setSum_salary(sum_sum_salary);
            mSumBean.setActual_salary(sum_actual_salary);
            mDatas.add(mSumBean);
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.ll_back:
                // 后退步骤
                switch (mStep){
                    case 2:
                        finish();
                        break;
                    case 3:
                        mStep = 2;
                        setStepData();
                        mDatas.clear();
                        mDatas.addAll(mDataAttendance);
                        setAttendanceTitle();
                        break;
                    case 4:
                        mStep = 3;
                        setStepData();
                        mDatas.clear();
                        mDatas.addAll(mDataSalary);
                        setCheckTitle();
                        break;
                    case 5:
                        finish();
                        break;
                }
                break;
            case R.id.tv_title_right:
                switch (mStep){
                    case 2:
                        mStep = 3;
                        mHScrollViews.clear();
                        setStepData();
                        checkAttendanceForm();
                        setCheckTitle();
                        break;
                    case 3:
                        mStep = 4;
                        mHScrollViews.clear();
                        setStepData();
                        createSalaryForm();
                        setSalaryFormTitle();
                        break;
                    case 4:
                        savaListData();
                        break;
                }
                break;
            case R.id.tv_title_right2:
                if (mStep == 2){
                    upDateListAllData();
                }
                break;
        }

    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        switch (mStep){
            case 2:
                finish();
                break;
            case 3:
                mStep = 2;
                setStepData();
                mDatas.clear();
                mDatas.addAll(mDataAttendance);
                setAttendanceTitle();
                break;
            case 4:
                mStep = 3;
                setStepData();
                mDatas.clear();
                mDatas.addAll(mDataSalary);
                setCheckTitle();
                break;
            case 5:
                finish();
                break;
        }
    }

    public void onScrollChanged(int l, int t, int oldl, int oldt){

        for (CHScrollCalculateView scrollView : mHScrollViews) {
            if (mTouchView != scrollView)
                scrollView.smoothScrollTo(l, t);
        }

    }

    /**
     * 设置标题栏
     */
    private void setStepData(){
        switch (mStep){
            case 2:
                mTvTitle.setText("核对" + mSelectDate.getMonth() +"月份考勤");
                mTvEdit.setVisibility(View.VISIBLE);
                mTvEdit.setText("全勤");
                mTvRight.setText("下一步");
                break;
            case 3:
                mTvTitle.setText("核对" + mSelectDate.getMonth() +"月份工资表");
                mTvEdit.setVisibility(View.GONE);
                mTvRight.setText("生成工资表");
                break;
            case 4:
                mTvTitle.setText(mSelectDate.getMonth() +"月份工资表");
                mTvEdit.setVisibility(View.GONE);
                mTvRight.setText("完成");
                break;
            case 5:
                mTvTitle.setText(mSelectDate.getMonth() +"月份工资表");
                mTvEdit.setVisibility(View.GONE);
                mTvRight.setText("");
                break;

        }
    }

    /**
     * 编辑框
     * @param title
     */
    public void showEditDialogMsg(String title,String content,int type) {
        String okText = "确定";
        String cancelText = this.getString(R.string.cancel);
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(mActivity);

        mDialogUtil.salaryEditStyle(title,content,okText,cancelText,null,type);
        mDialogUtil.setOnEditDialogListener(new AllDialogUtil.EditDialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog, EditText ed) {
                lDialog.dismiss();
                String number = ed.getEditableText().toString().trim();
                if (StringUtil.isEmpty(number)){
                    number = "0";
                }
                if (!StringUtil.isDecimal(number)){
                    showShortToast("数据格式不对");
                }else{
                    if (mStep == 2){
                        upDateListData(number);
                    }else if (mStep == 3){
                        upSalaryDateListData(number);
                    }
                }
            }

            @Override
            public void onCancelClick(Dialog lDialog, EditText ed) {
                lDialog.dismiss();
            }
        });

    }

    /**
     * 取消设置
     */
    public void showCancelDlg() {
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(this);
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        String notice = "是否取消生成工资表?";
        mDialogUtil.titleDeleteMsgStyle(okText, cancelText, notice);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                finish();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    /**
     * 更新考勤列表数据
     * @param data
     */
    private void upDateListData(String data){

        ((SalaryAttendanceBean)mDatas.get(mPositionY)).setData(mPositionX,data);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 更新考勤列表为全勤数据
     */
    private void upDateListAllData(){

        for (int i = 0; i < mDatas.size(); i++) {
            float total = ((SalaryAttendanceBean)mDatas.get(i)).getTotal();
            ((SalaryAttendanceBean)mDatas.get(i)).setWork_day(total);
            ((SalaryAttendanceBean)mDatas.get(i)).setApproval_business(0);
            ((SalaryAttendanceBean)mDatas.get(i)).setPaid_holidays(0);
            ((SalaryAttendanceBean)mDatas.get(i)).setApproval_out(0);
            ((SalaryAttendanceBean)mDatas.get(i)).setApproval_leave(0);
            ((SalaryAttendanceBean)mDatas.get(i)).setWork_leave_early_count(0);
            ((SalaryAttendanceBean)mDatas.get(i)).setWork_be_late_count(0);
            ((SalaryAttendanceBean)mDatas.get(i)).setUn_work(0);
            ((SalaryAttendanceBean)mDatas.get(i)).setOver_time(0);
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 更新工资列表数据
     * @param data
     */
    private void upSalaryDateListData(String data){

        ((SalaryAllBean)mDatas.get(mPositionY)).setPlus_or_minus(Float.parseFloat(data));
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 保存列表数据
     */
    private void savaListData(){

        if (mDatas.size() == 0)
            return;

        JSONArray member_salary = new JSONArray();
        try {
            for (int i = 0; i < mDatas.size() - 1; i++) {
                SalaryAllBean allData = (SalaryAllBean) mDatas.get(i);
                JSONObject member = new JSONObject();
                member.put("attendance_id",allData.get_id());
                member.put("user_name",allData.getUser_name());

                // 基本工资 自定义字段内容
                LinkedHashMap<String,SalaryFieldBean> fileds = allData.getFileds();
                member.put("base_salary",fileds.get("基本工资").getMoney());
                fileds.remove("基本工资");
                JSONArray salary_fields = new JSONArray();
                Iterator iterator = fileds.keySet().iterator();
                while (iterator.hasNext()){
                    Object object = iterator.next();
                    SalaryFieldBean fieldBean = fileds.get(object);
                    JSONObject field = new JSONObject();
                    field.put("order",fieldBean.getOrder());
                    field.put("name",fieldBean.getName());
                    field.put("money",Float.parseFloat(fieldBean.getMoney()));
                    salary_fields.put(field);
                }
                member.put("salary_fields",salary_fields);
                member.put("work_salary",allData.getWork_salary());

                member.put("meal_allowance",allData.getMeal_allowance());
                member.put("business_allowance",allData.getBusiness_allowance());
                member.put("overtime_allowance",allData.getOvertime_allowance());

                member.put("late_fine",allData.getLate_fine());
                member.put("leave_fine",allData.getLeave_fine());
                member.put("absent_fine",allData.getAbsent_fine());
                member.put("sum_salary",allData.getSum_salary());

                member.put("pension",allData.getPension());
                member.put("medical",allData.getMedical());
                member.put("unemployment",allData.getUnemployment());
                member.put("provident_fund",allData.getProvident_fund());

                member.put("plus_or_minus",allData.getPlus_or_minus());
                member.put("salary_tax",allData.getSalary_tax());
                member.put("actual_salary",allData.getActual_salary());

                member_salary.put(member);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        saveMemberSalary(member_salary.toString());
    }


    /**
     * 获取成员考勤列表
     */
    private void getAttendanceList(){
        waitDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MONTH, mSelectDate.getYear() + "_" + mSelectDate.getMonth()));
        GetSalaryAttendanceMsg msg = new GetSalaryAttendanceMsg(mHandler.obtainMessage(GET_ATTENDANCE_LIST));
        msg.mApi = AsynHttpClient.API_SALARY_GET_ATTENDANCE_LIST;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    /**
     * 保存工资表
     */
    private void saveMemberSalary(String member_salary){
        waitDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STR_MONTH, mSelectDate.getYear() + "_" + mSelectDate.getMonth()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MEMBER_SALARY, member_salary));
        WithoutObjMsg msg = new WithoutObjMsg(mHandler.obtainMessage(SAVE_MEMBER_SALARY));
        msg.mApi = AsynHttpClient.API_SALARY_SAVE;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    /**
     * 获取工资表
     */
    private void getMemberSalary(){
        waitDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_STR_MONTH, mSelectDate.getYear() + "_" + mSelectDate.getMonth()));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_SALARY, mSalaryId));
        GetSalaryAllDataMsg msg = new GetSalaryAllDataMsg(mHandler.obtainMessage(GET_MEMBER_SALARY));
        msg.mApi = AsynHttpClient.API_SALARY_LIST;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return mDatas == null ? 0:mDatas.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.salary_scroll_item_layout,null);
                holder.tvName = (TextView) convertView.findViewById(R.id.tv_excle_item);
                holder.layoutScroll = (CHScrollCalculateView) convertView.findViewById(R.id.ch_scroll_excle_item);
                holder.layoutSub = (LinearLayout) convertView.findViewById(R.id.ll_excle_item);
                convertView.setTag(holder);

            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            if (position%2 == 0){
                convertView.setBackgroundResource(R.color.excle_bg);
            }else{
                convertView.setBackgroundResource(R.color.white);
            }
            ArrayList<String> items = new ArrayList<>();
            switch (mStep){
                case 2:
                    SalaryAttendanceBean bean = (SalaryAttendanceBean) mDatas.get(position);
                    holder.tvName.setText(bean.getUser_name());
                    items.add(bean.getTotal() + "");
                    items.add(bean.getWork_day() + "");
                    items.add(bean.getApproval_business() + "");
                    items.add(bean.getPaid_holidays() + "");
                    items.add(bean.getApproval_leave() + "");
                    items.add(bean.getApproval_out() + "");
                    items.add(bean.getWork_leave_early_count() + "");
                    items.add(bean.getWork_be_late_count() + "");
                    items.add(bean.getUn_work() + "");
                    items.add(bean.getOver_time() + "");
                    break;
                case 3:
                    SalaryAllBean allBean = (SalaryAllBean) mDatas.get(position);
                    holder.tvName.setText(allBean.getUser_name());
                    items.add(allBean.getDay_salary() + "");
                    items.add(allBean.getWork_salary() + "");
                    items.add(allBean.getMeal_allowance() + "");
                    items.add(allBean.getBusiness_allowance() + "");
                    items.add(allBean.getOvertime_allowance() + "");
                    items.add(-allBean.getLate_fine() + "");
                    items.add(-allBean.getLeave_fine() + "");
                    items.add(-allBean.getAbsent_fine() + "");
                    items.add(allBean.getPlus_or_minus() + "");
                    break;
                case 4:
                case 5:
                    SalaryAllBean allDataDeleteTax = (SalaryAllBean) mDatas.get(position);
                    holder.tvName.setText(allDataDeleteTax.getUser_name());

                    // 基本工资和自定义字段
                    Map<String,SalaryFieldBean> fileds = allDataDeleteTax.getFileds();
                    Iterator iterator = fileds.keySet().iterator();
                    while (iterator.hasNext()){
                        Object object = iterator.next();
                        SalaryFieldBean filed = fileds.get(object);
                        String money = filed.getMoney();
                        if (StringUtil.isEmpty(money) || position == mDatas.size() -1){
                            items.add("0");
                        }else{
                            items.add(money);
                        }
                    }

                    items.add(allDataDeleteTax.getWork_salary() + "");

                    items.add(allDataDeleteTax.getMeal_allowance() + "");
                    items.add(allDataDeleteTax.getBusiness_allowance() + "");
                    items.add(allDataDeleteTax.getOvertime_allowance() + "");

                    items.add(-allDataDeleteTax.getLate_fine() + "");
                    items.add(-allDataDeleteTax.getLeave_fine() + "");
                    items.add(-allDataDeleteTax.getAbsent_fine() + "");
                    items.add(allDataDeleteTax.getPlus_or_minus() + "");

                    items.add(allDataDeleteTax.getSum_salary() + "");

                    items.add(-allDataDeleteTax.getPension() + "");
                    items.add(-allDataDeleteTax.getMedical() + "");
                    items.add(-allDataDeleteTax.getUnemployment() + "");
                    items.add(-allDataDeleteTax.getProvident_fund() + "");

                    items.add(-allDataDeleteTax.getSalary_tax() + "");
                    items.add(allDataDeleteTax.getActual_salary() + "");
                    break;
            }
            holder.layoutSub.removeAllViews();
            for (int i = 0; i < items.size(); i++) {
                TextView tv = new TextView(mContext);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 79.4f), ViewGroup.LayoutParams.MATCH_PARENT);
                tv.setGravity(Gravity.CENTER);
                tv.setLayoutParams(params);
                tv.setTextColor(getResources().getColor(R.color.black));
                tv.setText(floatFormat(items.get(i)));
                if (mStep == 2){
                    tv.setOnClickListener(new MyClickLinstener(i,position,0));
                }else if (mStep == 3 && i == items.size() - 1){ // 处理增减项数据
                    tv.setOnClickListener(new MyClickLinstener(i,position,1));
                }else if (position == mDatas.size() - 1 && (mStep == 4 || mStep == 5)){ // 处理合计数据
                    if (floatFormat(items.get(i)).equals("0")){
                        tv.setText("");
                    }
                }

                holder.layoutSub.addView(tv);
                View line = new View(mActivity);
                LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(Constants.dip2px(mContext, 0.6f), ViewGroup.LayoutParams.MATCH_PARENT);
                line.setLayoutParams(lineParams);
                line.setBackgroundResource(R.color.excle_line);
                holder.layoutSub.addView(line);
            }

            if (!mHScrollViews.isEmpty()) {
                int size = mHScrollViews.size();
                final int scrollX = mScrollViewCalculate.getScrollX();
                //第一次满屏后，向下滑动，有一条数据在开始时未加入
                if (scrollX != 0) {
                    final ViewHolder finalHolder = holder;
                    mListView.post(new Runnable() {
                        @Override
                        public void run() {
                            //当listView刷新完成之后，把该条移动到最终位置
                            finalHolder.layoutScroll.scrollTo(scrollX, 0);
                        }
                    });
                }
            }
            mHScrollViews.add(holder.layoutScroll);
            return convertView;
        }

        class ViewHolder{
            private TextView tvName;
            private LinearLayout layoutSub;
            private CHScrollCalculateView layoutScroll;
        }

        class MyClickLinstener implements View.OnClickListener {

            private int y_position;    // x 列数
            private int x_position;    // y 行数
            private String content;
            private int type;

            public MyClickLinstener(int x_position,int y_position,int type) {
                this.x_position = x_position;
                this.y_position = y_position;
                this.type = type;
            }

            public MyClickLinstener(int x_position,int y_position,String content,int type) {
                this.x_position = x_position;
                this.y_position = y_position;
                this.content = content;
                this.type = type;
            }

            @Override
            public void onClick(View view) {
                mPositionX = x_position;
                mPositionY = y_position;
                if ("0".equals(content) || "0.0".equals(content)){
                    content = "";
                }
                showEditDialogMsg(mTitleData.get(x_position),content,type);

            }
        }
    }
}
